package health_system.health_system.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Spring WebSocket handler implementation
 */
@Slf4j
@Component
public class SpringWebSocketHandler extends TextWebSocketHandler {

    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String sessionId = session.getId();
        sessions.put(sessionId, session);
        log.info("Spring WebSocket connection established: {}, total sessions: {}", sessionId, sessions.size());
        log.info("URI: {}", session.getUri());
        log.info("Headers: {}", session.getHandshakeHeaders());
        log.info("Attributes: {}", session.getAttributes());
        
        try {
            session.sendMessage(new TextMessage("Connected to Spring WebSocket Handler!"));
        } catch (IOException e) {
            log.error("Error sending welcome message", e);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        log.info("Received message from {}: {}", session.getId(), payload);
        
        try {
            session.sendMessage(new TextMessage("Spring Echo: " + payload));
        } catch (IOException e) {
            log.error("Error sending response message", e);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String sessionId = session.getId();
        sessions.remove(sessionId);
        log.info("Spring WebSocket connection closed: {}, status: {}, remaining sessions: {}", 
                sessionId, status, sessions.size());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        String sessionId = session.getId();
        log.error("Spring WebSocket transport error: {}, error: {}", 
                sessionId, exception.getMessage(), exception);
        
        try {
            session.close(CloseStatus.SERVER_ERROR);
        } catch (IOException e) {
            log.error("Error closing WebSocket session after error", e);
        }
        
        sessions.remove(sessionId);
    }
} 